<template>
  <div class="history-container">
    <div class="page-section">
      <div class="page-title">历史会话</div>
      <el-form ref="searchFrom" :model="searchFrom" inline label-width="80px">
        <el-form-item label="会话开始" prop="dateRange">
          <el-date-picker
            size="mini"
            v-model="searchFrom.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            :clearable="false"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="客户类型" prop="type">
          <el-select v-model="searchFrom.type" placeholder="请选择类型" clearable>
            <el-option label="游客" value="4"> </el-option>
            <el-option label="用户" value="3"> </el-option>
            <el-option label="客户" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="userPhone">
          <el-input
            v-model="searchFrom.userPhone"
            placeholder="输入手机号码"
            :clearable="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户号" prop="clientId">
          <el-input
            v-model="searchFrom.clientId"
            placeholder="输入客户号"
            :clearable="false"
          ></el-input>
        </el-form-item>
        <el-form-item label="会话标签" prop="labelCode">
          <el-select
          clearable
            multiple
            collapse-tags
            v-model="searchFrom.labelCode_"
            placeholder="请选择类型"
          >
            <el-option
              :label="mark.dictKey"
              :value="mark.id"
              v-for="mark in markList"
              :key="mark.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">搜索</el-button>
          <!-- <el-button @click="reset">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="chat-list">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#f2f2f2' }"
      >
        <el-table-column
          prop="talkerType"
          label="用户类型"
          width="180"
          header-align="center"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.talkerType | talkerType }}
          </template>
        </el-table-column>
        <el-table-column
          prop="userPhone"
          label="手机号码"
          width="180"
          header-align="center"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="clientId"
          label="客户号"
          width="180"
          header-align="center"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.talkerType == '2' ? row.clientId: ''}}
          </template>
        </el-table-column>
        <el-table-column
          prop="waiterId"
          label="最后接入客服"
          width="180"
          header-align="center"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.waiterId }}
          </template>
        </el-table-column>
        <el-table-column
          prop="stringCreatTime"
          label="开始会话时间"
          header-align="center"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.stringCreatTime |  stringCreatTime}}
          </template>
        </el-table-column>
        <el-table-column
          prop="labelDesc"
          label="会话标签"
          header-align="center"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.labelDesc | labelDesc }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
          width="180"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="checkout(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="currentChangeHandle"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
      >
      </el-pagination>
    </div>
    <div class="dialog" v-loading="loading">
      <el-dialog :visible.sync="visible" width="40%">
        <template slot="title">
          <div class="dialog-title">{{ dialogUserName }}</div>
        </template>
        <div>
          <div class="recoders" v-if="recoders.length">
            <div class="message" v-for="(message, i) in recoders" :key="i">
              <history-passage :message="message"></history-passage>
            </div>
          </div>
          <div class="no-data" v-else>
            <span>暂无数据</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import HistoryPassage from "@/components/history-passage";
import { queryMeetingList, queryMeetingDetail, getMarks } from "@/api/chat";
import { mapState } from "vuex";
import { timeformat } from "./utils";
// import { queryMarkTreeList } from "@/api/knowlegeBase";
import { deepClone } from "@/utils/common";
let that = this;
export default {
  name: "history-conversation",
  data() {
    return {
      searchFrom: {
        dateRange: [new Date(), new Date()],
        labelCode_: [],
        type: null,
        clientId: "",
        userPhone: "",
      },
      tableData: [],
      loading: false,
      visible: false,
      recoders: [],
      pageSize: 10,
      pageNum: 1,
      total: 0,
      markList: [],
      dialogUserName: "用户记录",
    };
  },
  components: {
    HistoryPassage,
  },
  computed: {
    ...mapState(["idStore"]),
    pickerOptions: () => {
      return {
        disabledDate(time) {
          return time.getTime() > new Date().getTime() + 24 * 60 * 60;
        },
      };
    },
  },
  beforeCreate: function () {
    that = this;
  },
  filters: {
    talkerType(val) {
      if (!val) {
        return "";
      } else {
        if (val == "2") {
          return "客户";
        }
        if (val == "3") {
          return "用户";
        }
        if (val == "4") {
          return "游客";
        }
      }
    },
    labelDesc(val) {
      let res = [];
      if (val) {
        const ids = val.split(",");
        ids.forEach((id) => {
          that.markList.forEach((mark) => {
            if (id == mark.id) {
              res.push(mark.dictKey);
            }
          });
        });
      }
      return res.join(",");
    },
    stringCreatTime(val){
         if(!val){
           return ''
         }
      const index = val.indexOf('.')
      if(index > 0){
        return val.slice(0,index)
      }
      return  val

    }
  },
  mounted() {
    this.getMarkList();
    if (this.idStore.waiterId) {
      this.onSubmit();
    }
  },
  methods: {
    getList(params) {
      this.loading = true;
      queryMeetingList(params)
        .then((res) => {
          const {
            data: { list, total },
          } = res;
          this.tableData = list;
          this.total = total;
        })
        .catch(() => {
          this.$message.error(`获取记录异常`);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onSubmit() {
      if (!this.idStore.waiterId) {
        this.$message.warning("客服id不存在");
        return;
      }
      let [start, end] = this.searchFrom.dateRange;
      start = timeformat(start).replace(/T.*/, "T00:00:00");
      end = timeformat(end).replace(/T.*/, "T23:59:59");
      const params = {
        talkerType: 1,
        talker: this.idStore.waiterId,
        startTime: start,
        endTime: end,
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        labelCode:
          this.searchFrom.labelCode_.length == 0
            ? null
            : this.searchFrom.labelCode_,
      };
      this.getList({ ...params, ...this.searchFrom });
    },
    reset() {
      this.$refs["searchFrom"].resetFields();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNum = val;
      this.onSubmit();
    },
    checkout(data) {
      this.visible = true;
      this.loading = true;
      this.recoders = [];
      const params = {
        // talkerType: "member",
        // talker: data.talkers,
        pageSize: 1000,
        pageNum: 1,
        meetingId: data.id,
      };
      queryMeetingDetail(params)
        .then((res) => {
          const {
            data: { list },
          } = res;
          if (list.length) {
            let row = list.find((item) => item.talkerType == 1);
            let titleRow = deepClone(row);
            if (titleRow) {
              titleRow["title"] = true;
            } else {
              titleRow = { title: true, serverTime: list[0].serverTime };
            }
            list.unshift(titleRow);
            this.recoders = list.filter(item=>item.contentType !== '0x58') //过滤掉评价消息
          }
        })
        .catch(() => {
          this.$message.error(`获取记录异常`);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 获取标签
    getMarkList() {
      const params = ["im-data"];
      getMarks(params)
        .then((res) => {
          let {
            data: { result },
          } = res;
          const parentMarkList = result[0]["im-data"];
          const keys = parentMarkList.map((item) => item.routeStr);
          getMarks(keys).then((marks) => {
            let {
              data: { result },
            } = marks;
            Object.values(result[0]).forEach((item) => {
              this.markList = this.markList.concat(item);
            });
            this.markList.forEach((mark) => {
              mark.id = String(mark.id);
            });
          });
        })
        .catch(() => {
          // this.$message.error(`获取标签异常`);
          throw new Error('获取标签接口异常')
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  .dialog-title {
    height: 15px;
    line-height: 15px;
  }
  ::v-deep .el-dialog__header {
    padding: 10px 20px;
    border-bottom: 1px solid #e6e6e6;
  }
  ::v-deep .el-dialog__body {
    padding: 0 0 10px;
  }
  ::v-deep .el-dialog__headerbtn {
    top: 10px;
  }
  ::v-deep .title-item {
    border-top: none;
    height: 35px;
    line-height: 35px;
  }
  .no-data {
    height: 50px;
    line-height: 50px;
    text-align: center;
    span {
      opacity: 0.5;
    }
  }
}
</style>